package com.ruoyi.system.service.impl;
import java.util.concurrent.TimeUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.HttpMethod;
import com.ruoyi.system.domain.ChatHistory;
import com.ruoyi.system.mapper.ChatHistoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ChatMessagesMapper;
import com.ruoyi.system.domain.ChatMessages;
import com.ruoyi.system.domain.ChatMessagesDTO;
import com.ruoyi.system.service.IChatMessagesService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

@Service
public class ChatMessagesServiceImpl implements IChatMessagesService {
    @Autowired
    private ChatMessagesMapper chatMessagesMapper;
    @Autowired
    private ChatHistoryMapper chatHistoryMapper;
    @Override
    public List<ChatMessagesDTO> getChatMessages(String chatId) {
        List<ChatMessages> messages = chatMessagesMapper.selectChatMessagesByChatId(chatId);
        return messages.stream().map(this::convertToDTO).collect(Collectors.toList());
    }
    // 休眠 1 秒
    @Override
    @Transactional
    public ChatMessagesDTO addChatMessage(String chatId, String messageContent) {
        // 1. 新增聊天记录
        ChatMessages message = new ChatMessages();
        message.setChatId(chatId);
        message.setRole("user"); // 默认角色
        message.setMessageContent(messageContent);
        message.setTimestamp(new Date());
//        chatMessagesMapper.insertChatMessage(message);
        // 2. 调用大模型获取回复
        String aiResponse = callAIModel(chatId, messageContent);


        try {
            TimeUnit.SECONDS.sleep(1); // 休眠 1 秒
            System.out.println("1 秒后执行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 3. 存储AI回复
        ChatMessages aiMessage = new ChatMessages();
        aiMessage.setChatId(chatId);
        aiMessage.setRole("assistant");
        aiMessage.setMessageContent(aiResponse);
        aiMessage.setTimestamp(new Date());
        chatMessagesMapper.insertChatMessage(message);
        chatMessagesMapper.insertChatMessage(aiMessage);

        // 2. 更新对应聊天历史的最后消息时间
        ChatHistory history = new ChatHistory();
        history.setChatId(chatId);
        history.setLastMessageTime(aiMessage.getTimestamp());
        chatHistoryMapper.updateLastMessageTime(history);

        return convertToDTO(aiMessage);
    }

    private ChatMessagesDTO convertToDTO(ChatMessages message) {
        ChatMessagesDTO dto = new ChatMessagesDTO();
        dto.setChatId(message.getChatId());
        dto.setRole(message.getRole());
        dto.setMessageContent(message.getMessageContent());
        dto.setTimestamp(message.getTimestamp());
        return dto;
    }

    private String callAIModel(String chatId, String userMessage) {
        try {
            // 创建请求体
            Map<String, String> requestBody = new HashMap<>();
            requestBody.put("prompt", userMessage);  // 使用userMessage替换prompt内容

            // 创建HTTP请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 创建HTTP实体
            HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 使用RestTemplate发送POST请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> response = restTemplate.exchange(
                    "http://127.0.0.1:8000/chat",
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            String responseBody = response.getBody();
            if (responseBody != null && responseBody.startsWith("\"") && responseBody.endsWith("\"")) {
                responseBody = responseBody.substring(1, responseBody.length() - 1);
            }

            // 将换行符\n替换为HTML的<br>标签
            if (responseBody != null) {
                responseBody = responseBody.replace("\\n", "<br/>");
            }
            // 返回API响应内容
            return responseBody;
        } catch (Exception e) {
            e.printStackTrace();  // 实际项目中建议使用日志记录
            return "抱歉，AI服务暂时不可用";
        }
    }
}